/*
 * @Author: your name
 * @Date: 2019-11-19 09:05:30
 * @LastEditTime: 2019-11-23 09:52:01
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \YouYouFo\you-you-go\src\store\index.js
 */

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodsList: localStorage.getItem('goodsList') ? JSON.parse(localStorage.getItem('goodsList')) : [{
      id: 90,
      count: 1,
      price: 5780,
    }, {
      id: 88,
      count: 1,
      price: 2199,
    }, {
      id: 89,
      count: 1,
      price: 4799,
    }],
  },
  mutations: {

    /**
     * @name: add2GoodsList
     * @msg: 将商品加入购物车列表,如果已存在数量相加
     * @param: [Object] {id,count,price}
     * @return: 
     */
    add2GoodsList(state, goodsInfo) {
      var flag = true
      state.goodsList.some((item) => {
        if (item.id === goodsInfo.id) {
          flag = false
          item.count += parseInt(goodsInfo.count)
          return true
        }
      })
      if (flag) {
        state.goodsList.push(goodsInfo)
      }
      localStorage.setItem('goodsList', JSON.stringify(state.goodsList))
    },

    /**
     * @name: updateGoodsInfo
     * @msg: 更新商品信息
     * @param:[object] {id,count}
     * @return: 
     */
    updateGoodsInfo(state, goodsInfo) {
      state.goodsList.some(item => {
        if (item.id === goodsInfo.id) {
          item.count = parseInt(goodsInfo.count)
          return true
        }
      })
      localStorage.setItem('goodsList', JSON.stringify(state.goodsList))
    },

    /**
     * @name: removeGoods
     * @msg: 移除商品
     * @param: [Number]
     * @return: 
     */
    removeGoods(state, id) {
      state.goodsList.some((item, index) => {
        if (item.id === id) {
          state.goodsList.splice(index, 1)
          return true
        }
      })
      localStorage.setItem('goodsList', JSON.stringify(state.goodsList))

    }
  },
  actions: {},
  modules: {},
  getters: {
    // 获取所有数量
    getAllCount(state) {
      var count = 0
      state.goodsList.forEach((item) => {
        count += item.count
      })
      return count
    },
    // 获取商品总价
    getTotalPrice(state) {
      var total = 0
      state.goodsList.forEach(item => {
        total += item.price * item.count
      });
      return total
    },
    // 获取商品总数量
    getGoodsCount(state) {
      var obj = {}
      state.goodsList.forEach(item => {
        obj[item.id] = item.count
      });
      return obj
    },

  }
})
